Last but not least, it is important to understand the role of the C# partial keyword. A production level class could very easily consist of hundreds and hundreds of lines of code. As well, given that a typical class is defined within a single *.cs file, you could end up with a very long file indeed. When you are creating your classes, it is often the case that much of the code can be basically ignored once accounted for. For example, field data, properties, and constructors tend to remain as-is during production, while methods tend to be modified quite often.
If you wish, you can partition a single class across multiple C# files, to isolate the boilerplate code from more readily useful members. To illustrate, open up the EmployeeApp project you created previously in this chapter into Visual Studio, and once you have done so, open the Employee.cs file for editing. Currently, this single file contains code of all aspects of the class:
class Employee { // Field Data // Constructors // Methods // Properties }
Using partial classes, you could choose to move the constructors and field data into a brand new file named Employee.Internal.cs (please note, the name of the file is irrelevant; here I just tacked on the work internal to represent the guts of the class). The first step is to add the partial keyword to the current class definition and cut the code to be placed into the new file:
// Employee.cs partial class Employee { // Methods // Properties }
Next, assuming you have inserted a new class file into your project, you can move the data fields and constructors to the new file using a simple cut/paste operation. In addition, you must add the partial keyword to this aspect of the class definition. For example:
// Employee.Internal.cs partial class Employee { // Field data // Constructors }
Note Remember! Every aspect of a partial class definition must be marked with the partial keyword.
Once you compile the modified project, you should see no difference whatsoever. The whole idea of a partial class is only realized during design time. Once the application has been compiled, there is just a single, unified class within the assembly. The only requirement when defining partial types is that the type's name (Employee in this case) is identical and defined within the same .NET namespace.
To be honest, you will most likely not need to make use of partial class definitions too often. However, Visual Studio uses them in the background all the time. Later in this book when you start to look into GUI application development in Windows Forms, Windows Presentation Foundation, or ASP.NET, you'll see that Visual Studio isolates designer generated code into a partial class, leaving you to focus on your application specific programming logic.
Source Code The EmployeeApp project can be found under the Chapter 5 subdirectory.